All files / web/src/app/api/curriculum/[playerId]/attachments/[attachmentId]/file route.ts

0% Statements 0/86
0% Branches 0/1
0% Functions 0/1
0% Lines 0/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87                                                                                                                                                                             
/**
 * API route for serving practice attachment files
 *
 * GET /api/curriculum/[playerId]/attachments/[attachmentId]/file
 *
 * Serves the actual image file for a practice attachment.
 * Authorization is checked to ensure only parents and teachers can access.
 */

import { readFile, stat } from 'fs/promises'
import { NextResponse } from 'next/server'
import { join } from 'path'
import { eq } from 'drizzle-orm'
import { db } from '@/db'
import { practiceAttachments } from '@/db/schema'
import { canPerformAction } from '@/lib/classroom'
import { getUserId } from '@/lib/viewer'
import { withAuth } from '@/lib/auth/withAuth'

/**
 * GET - Serve attachment file
 */
export const GET = withAuth(async (_request, { params }) => {
  try {
    const { playerId, attachmentId } = (await params) as { playerId: string; attachmentId: string }

    if (!playerId || !attachmentId) {
      return NextResponse.json({ error: 'Player ID and Attachment ID required' }, { status: 400 })
    }

    // Authorization check
    const userId = await getUserId()
    const canView = await canPerformAction(userId, playerId, 'view')
    if (!canView) {
      return NextResponse.json({ error: 'Not authorized' }, { status: 403 })
    }

    // Get attachment record
    const attachment = await db
      .select()
      .from(practiceAttachments)
      .where(eq(practiceAttachments.id, attachmentId))
      .get()

    if (!attachment) {
      return NextResponse.json({ error: 'Attachment not found' }, { status: 404 })
    }

    // Verify the attachment belongs to the specified player
    if (attachment.playerId !== playerId) {
      return NextResponse.json({ error: 'Attachment not found' }, { status: 404 })
    }

    // Build file path
    const filepath = join(
      process.cwd(),
      'data',
      'uploads',
      'players',
      playerId,
      attachment.filename
    )

    // Check if file exists
    try {
      await stat(filepath)
    } catch {
      console.error(`Attachment file not found: ${filepath}`)
      return NextResponse.json({ error: 'File not found' }, { status: 404 })
    }

    // Read and serve file
    const fileBuffer = await readFile(filepath)

    return new NextResponse(new Uint8Array(fileBuffer), {
      headers: {
        'Content-Type': attachment.mimeType,
        'Content-Length': attachment.fileSize.toString(),
        'Cache-Control': 'private, max-age=31536000', // Cache for 1 year (files are immutable)
      },
    })
  } catch (error) {
    console.error('Error serving attachment:', error)
    return NextResponse.json({ error: 'Failed to serve attachment' }, { status: 500 })
  }
})